package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
)

func upload_client(conn net.Conn, fileAllInfo string) {

	// 文件路径
	path := strings.Split(fileAllInfo, " ")[1]

	// 打开文件获得句柄
	f, _ := os.Open(path)
	defer f.Close()

	reader := bufio.NewReader(f)
	for {
		uploadData, err := reader.ReadBytes('\n')
		if err == io.EOF {
			conn.Write([]byte(uploadData))
			break
		}
		conn.Write(uploadData)
	}

}

func down_client() {

}
func main() {

	for {
		// 拨号建联
		conn, err := net.Dial("tcp", "127.0.0.1:8080")
		if err != nil {
			fmt.Println(err)
		}
		fmt.Printf("put/down >>>：")
		//标准输入，传文件的路径
		reader := bufio.NewReader(os.Stdin)
		input, _ := reader.ReadString('\n') // 阻塞

		// 给输入的值去个空
		input = strings.TrimSpace(input)
		fmt.Println(input)
		// input = put + path
		cmd := strings.Split(input, " ")[0]

		path := strings.Split(input, " ")[1]

		// fileInfo
		fileInfo, _ := os.Stat(path)
		fileName := fileInfo.Name()
		fileSize := fileInfo.Size()
		fileSizeStr := strconv.FormatInt(fileSize, 10)

		fileAllInfo := cmd + " " + path + " " + fileName + " " + fileSizeStr
		conn.Write([]byte(fileAllInfo))

		switch cmd {
		case "put":
			upload_client(conn, fileAllInfo)
		case "down":
			down_client()
		case "":
			continue
		default:
			fmt.Println("输入错误！请重新输入命令：down/put")

		}
	}

}
